import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab

G = nx.DiGraph()

G.add_edges_from([('A', 'B'), ('C', 'G'), ('G', 'D')], weight=1)
G.add_edges_from([('D', 'A'), ('D', 'E'), ('B', 'D'), ('D', 'E')], weight=2)
G.add_edges_from([('B', 'C'), ('E', 'F')], weight=3)
G.add_edges_from([('C', 'F')], weight=4)
G.add_edges_from([('G', 'F')], weight=5)

val_map = {'A': 1.0,
           'D': 0.5714285714285714,
           'H': 0.0}

values = [val_map.get(node, 0.45) for node in G.nodes()]

edge_labels = dict([((u, v,), d['weight'])
                    for u, v, d in G.edges(data=True)])
red_edges = [('C', 'D'), ('D', 'A')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]
# pos = nx.random_layout(G)#随机布局方式，节点容易发生重叠。
# pos = nx.circular_layout(G)#圆形布局，比较规则，但是箭头经常发生交叉。
# pos = nx.shell_layout(G)#差不多是环形布局
# pos = nx.spectral_layout(G)  # 使用正交向量。
pos = nx.spring_layout(G)  # Fruchterman-Reingold 算法生成的有向图，还是这个靠谱。
nx.draw(G, pos, node_color='yellow', node_size=500, edge_color=edge_colors)
nx.draw_networkx_labels(G, pos, font_size=10, font_family='sans-serif')

nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
# 以下为求解最短路径
print(nx.shortest_path_length(G, 'C', 'A'))  # 这样会出错，对于有向图，不能判断方向。
print(nx.shortest_path_length(G,'C',"A",weight='weight')) #这样才能返回正确的结果。
print(nx.dijkstra_path(G, 'C', 'A', weight='weight'))#依次返回路径经过的节点。
print(nx.dijkstra_path_length(G, 'C', 'A', weight='weight'))#返回路径的长度
pylab.show()
